package com.gwsdk.paysdk.acitvityV2.fragment;

import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;

import com.gwsdk.paysdk.acitvityV2.GWMainMenuActivity;
import com.gwsdk.paysdk.acitvityV2.adapter.GWPacksAdapter;
import com.gwsdk.paysdk.config.GWConstant;
import com.gwsdk.paysdk.entity.GamePackInfo;
import com.gwsdk.paysdk.http.RequestParamUtil;
import com.gwsdk.paysdk.http.RequestUtil;
import com.gwsdk.paysdk.utils.GWErrorCodeUtils;
import com.gwsdk.paysdk.utils.GWInflaterUtils;
import com.gwsdk.paysdk.utils.GWLog;
import com.gwsdk.paysdk.utils.ToastUtil;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.apache.http.entity.StringEntity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GWMineGiftFragment extends GWBaseFragment{

    private ImageView backItem;
    private ListView listView;
    private View loadingView;
    private GWPacksAdapter adapter;
    private View gwNodata;
    private List<GamePackInfo> packList = new ArrayList<>();
    @Override
    public int setContentView() {
        return GWInflaterUtils.getLayout(getActivity(),"gw_fragment_mine_gift");
    }

    @Override
    public void initView(View view) {
        backItem = view.findViewById(GWInflaterUtils.getControl(getActivity(),"btn_back"));
        backItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });
        gwNodata = view.findViewById(GWInflaterUtils.getControl(getActivity(),"not_data_view"));
        loadingView = view.findViewById(GWInflaterUtils.getControl(getActivity(),"loading_view"));
        listView = view.findViewById(GWInflaterUtils.getControl(getActivity(),"list_view"));
        adapter = new GWPacksAdapter(getActivity());
        listView.setAdapter(adapter);
        adapter.setReceiveClick(new GWPacksAdapter.OnReceiveClick() {
            @Override
            public void onClick(GamePackInfo packInfo) {
                if (packInfo.getPackStatus().equals("1")) {
                    ClipboardManager cmb = (ClipboardManager)getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                    cmb.setText(packInfo.getPackCode());
                    ToastUtil.show(getActivity(),"复制成功");
                }
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                GamePackInfo gamePackInfo = packList.get(i);
                GWMainMenuActivity activity = (GWMainMenuActivity) getActivity();
                GWGiftDetailsFragment detailsFragment = new GWGiftDetailsFragment();
                Bundle bundle = new Bundle();
                bundle.putSerializable("packInfo",gamePackInfo);
                detailsFragment.setArguments(bundle);
                activity.addOtherFragment(detailsFragment);
            }
        });

    }

    @Override
    public void getData() {

        Map<String, String> map = new HashMap<String, String>();

        String param = RequestParamUtil.getRequestParamString(map);
        if (TextUtils.isEmpty(param)) {
            GWLog.e("GWMineGiftFragment", "fun#post param is null");
            return;
        }
        RequestParams params = new RequestParams();
        try {
            params.setBodyEntity(new StringEntity(param.toString()));
        } catch (UnsupportedEncodingException e) {
            params = null;
        }

        if (param == null) return;
        HttpUtils http = new HttpUtils();

        String url = GWConstant.getInstance().getMyGiftListUrl();
        http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                loadingView.setVisibility(View.GONE);
                String response = RequestUtil.getResponse(responseInfo);
//                GWLog.e(TAG,"游戏消费记录："+response);
                int status;
                try {
                    JSONObject json = new JSONObject(response);
                    status = json.optInt("code");
                    JSONArray data = json.getJSONArray("data");
                    if (status == 200 ) {
                        List<GamePackInfo> gamePackList = getGamePackList(data);
                        for (GamePackInfo info : gamePackList){
                            info.setPackStatus("1");
                        }
                        packList.clear();
                        packList.addAll(gamePackList);
                        if (packList.size() <= 0){
                            gwNodata.setVisibility(View.VISIBLE);
                        }else {
                            gwNodata.setVisibility(View.GONE);
                            listView.setVisibility(View.VISIBLE);
                        }
                        adapter.setPackList(packList);

                    } else {
                        String msg;
                        if (!TextUtils.isEmpty(json.optString("msg"))) {
                            msg = json.optString("msg");
                        } else {
                            msg = GWErrorCodeUtils.getErrorMsg(json.optInt("code"));
                        }
                        gwNodata.setVisibility(View.VISIBLE);
                        ToastUtil.show(getActivity(),msg);
                    }
                } catch (JSONException e) {
                    gwNodata.setVisibility(View.VISIBLE);
                    ToastUtil.show(getActivity(),"获取游戏礼包数据异常");
//                    GWLog.e(TAG, "fun#post JSONException:" + e);
                } catch (Exception e) {
                    gwNodata.setVisibility(View.VISIBLE);
                }

            }

            @Override
            public void onFailure(HttpException e, String s) {
                loadingView.setVisibility(View.GONE);
                ToastUtil.show(getActivity(),s);
            }
        });

    }


    protected List<GamePackInfo> getGamePackList(JSONArray jsonArray) {
        if (null == jsonArray) {
            return new ArrayList<GamePackInfo>();
        }
        List<GamePackInfo> packInfoList = new ArrayList<GamePackInfo>();
        try {
            for (int i = 0; i < jsonArray.length(); i++) {// 遍历JSONArray
                GamePackInfo packInfo = new GamePackInfo();

                JSONObject jsonPack = jsonArray.getJSONObject(i);
                packInfo.setGiftId(jsonPack.optString("gift_id"));
                packInfo.setPackName(jsonPack.optString("giftbag_name"));
                packInfo.setVipLimit(jsonPack.optInt("vip"));
                packInfo.setGameId(jsonPack.optString("game_id"));
                packInfo.setGameName(jsonPack.optString("game_name"));
                packInfo.setPackCode(jsonPack.optString("novice"));
                packInfo.setSurplus(jsonPack.optInt("surplus",0));
                packInfo.setPackDesc(jsonPack.optString("digest"));
                packInfo.setPackImageUrl(jsonPack.optString("icon"));
                packInfo.setNovice(jsonPack.optString("novice"));
                packInfo.setDesribe(jsonPack.optString("desribe"));
                packInfo.setDigest(jsonPack.optString("digest"));
//				packInfo.setPackStatus(jsonPack.optString("status"));
                packInfo.setPackStatus(jsonPack.optString("received"));
                String mEndTime = jsonPack.optString("end_time");
                if (!mEndTime.equals("0")) {
                    packInfo.setStartTime(jsonPack.optString("start_time"));
                    packInfo.setEndTime(jsonPack.optString("end_time"));
                } else {
                    packInfo.setEndTime("0");
                }
                packInfoList.add(packInfo);
            }

        } catch (JSONException e) {

        }

        return packInfoList;
    }





}
